package com.mdinfo.base.common.bean;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by superbone on 2017/12/4.
 */
@Data
public class Tree<T> {

    private T data;
    private Integer id;
    private Integer pid;
    private String name;
    private List<Tree<T>> children = new ArrayList<>();

    /**
     * 生成树结构
     */
    public static <T> List<Tree<T>> createTree(List<Tree<T>> list,Integer pid){
        if(pid==null || pid<0){
            pid = 0;
        }
        List<Tree<T>> reList = new ArrayList<>();
        for(Tree<T> tree : list){
            if(tree.getPid().intValue()==pid.intValue()){
                tree.setChildren(createTree(list,tree.getId()));
                reList.add(tree);
            }
        }
        return reList;
    }

    /**
     * 从完整树结构中获取自己为顶层的树
     */
    public static <T> Tree<T> getMyTree(Tree<T> root, int id){

        Tree<T> result = null;
        if(root.getId().intValue()==id){
            result = root;
        }else{
            for(Tree<T> child : root.getChildren()){
                return getMyTree(child,id);
            }
        }
        return result;
    }

    /**
     * 获取树结构的id集合
     */
    public static <T> List<Integer> listMyId(Tree<T> tree,List<Integer> result){
        if(result==null){
            result = new ArrayList<>();
        }
        result.add(tree.getId());
        for(Tree<T> child : tree.getChildren()){
            listMyId(child,result);
        }
        return result;
    }
}
